const express = require('express');
const router = express.Router();
const moment = require('moment');
const rds = require('../rds');
const tutils = require('../tutils');

// 我的名片管理页面（需登录）
router.get('/my', async (req, res) => {
    try {
        const uid = req.session.totemUID;

        if (!uid) {
            return res.redirect('/apps/login');
        }

        // 获取用户名片信息
        const [[card]] = await rds.query(
            'SELECT * FROM user_cards WHERE uid = ?',
            [uid]
        );

        // 获取用户基本信息
        const [[user]] = await rds.query(
            'SELECT uid, real_name, phone FROM eb_user WHERE uid = ?',
            [uid]
        );

        res.render('card/manage', {
            title: '我的名片',
            card: card ? JSON.parse(card.card_json) : null,
            user,
            hasCard: !!card
        });
    } catch (error) {
        console.error('名片管理页面错误:', error);
        res.status(500).send('服务器错误');
    }
});

// 名片编辑页面（需登录）
router.get('/edit', async (req, res) => {
    try {
        const uid = req.session.totemUID;

        if (!uid) {
            return res.redirect('/apps/login');
        }

        // 获取用户名片信息
        const [[card]] = await rds.query(
            'SELECT * FROM user_cards WHERE uid = ?',
            [uid]
        );

        // 获取用户基本信息
        const [[user]] = await rds.query(
            'SELECT uid, real_name, phone FROM eb_user WHERE uid = ?',
            [uid]
        );

        res.render('card/edit', {
            title: '编辑名片',
            card: card ? JSON.parse(card.card_json) : null,
            user,
            hasCard: !!card
        });
    } catch (error) {
        console.error('名片编辑页面错误:', error);
        res.status(500).send('服务器错误');
    }
});

// 名片展示页面（公开访问）
router.get('/:uid', async (req, res) => {
    try {
        const { uid } = req.params;

        // 获取名片信息
        const [[card]] = await rds.query(
            'SELECT * FROM user_cards WHERE uid = ?',
            [uid]
        );

        if (!card) {
            return res.render('warn', {
                title: '名片不存在',
                message: '该用户的名片尚未创建',
                description: '请联系名片主人创建名片',
                icon: 'weui-icon-warn weui-icon_msg'
            });
        }

        // 解析JSON数据
        const cardData = JSON.parse(card.card_json);

        // 设置微信分享meta标签
        const shareData = {
            title: `${cardData.name} - ${cardData.org_name}`,
            description: card.card_intro || cardData.org_intro || '查看我的名片',
            image: card.card_thumb || cardData.avatar || '',
            url: `${req.protocol}://${req.get('host')}/apps/card/${uid}`
        };

        res.render('card/display', {
            title: `${cardData.name}的名片`,
            card: cardData,
            shareData,
            uid
        });
    } catch (error) {
        console.error('名片展示页面错误:', error);
        res.status(500).send('服务器错误');
    }
});

// 保存名片信息API
router.post('/save', async (req, res) => {
    try {
        const uid = req.session.totemUID;

        if (!uid) {
            return res.status(401).json({ success: false, message: '请先登录' });
        }

        const cardData = req.body;

        // 验证必填字段
        if (!cardData.name) {
            return res.status(400).json({ success: false, message: '姓名不能为空' });
        }

        // 检查是否已存在名片
        const [[existingCard]] = await rds.query(
            'SELECT id FROM user_cards WHERE uid = ?',
            [uid]
        );

        const cardJson = JSON.stringify(cardData);
        const cardIntro = cardData.org_intro || cardData.org_name || cardData.name;
        const cardThumb = cardData.avatar || cardData.org_logo || '';

        if (existingCard) {
            // 更新现有名片
            await rds.query(
                'UPDATE user_cards SET card_json = ?, card_intro = ?, card_thumb = ?, updated_at = CURRENT_TIMESTAMP WHERE uid = ?',
                [cardJson, cardIntro, cardThumb, uid]
            );
        } else {
            // 创建新名片
            await rds.query(
                'INSERT INTO user_cards (uid, card_json, card_intro, card_thumb) VALUES (?, ?, ?, ?)',
                [uid, cardJson, cardIntro, cardThumb]
            );
        }

        res.json({ success: true, message: '名片保存成功' });
    } catch (error) {
        console.error('保存名片错误:', error);
        res.status(500).json({ success: false, message: '服务器错误' });
    }
});

// 获取名片信息API
router.get('/api/:uid', async (req, res) => {
    try {
        const { uid } = req.params;

        const [[card]] = await rds.query(
            'SELECT * FROM user_cards WHERE uid = ?',
            [uid]
        );

        if (!card) {
            return res.status(404).json({ success: false, message: '名片不存在' });
        }

        res.json({
            success: true,
            data: {
                ...card,
                card_json: JSON.parse(card.card_json)
            }
        });
    } catch (error) {
        console.error('获取名片信息错误:', error);
        res.status(500).json({ success: false, message: '服务器错误' });
    }
});

module.exports = router;